package com.uinnova.product.eam.web.util;

import com.binary.core.http.URLResolver;
import com.binary.core.io.FileSystem;
import com.binary.core.io.support.FileResource;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.Local;
import com.binary.framework.exception.ControllerException;
import com.binary.framework.util.ControllerUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ControllerResourceUtil extends ControllerUtils {

    public static ModelAndView returnResource(HttpServletRequest request, HttpServletResponse response, FileResource resource, String contentType, boolean openWindow, String fileName) {
        if (resource != null && resource.exists()) {
            if (BinaryUtils.isEmpty(contentType)) {
                contentType = "application/octet-stream";
            }

            if (BinaryUtils.isEmpty(fileName)) {
                fileName = resource.getName();
            }

            response.setContentType(contentType);
            if (!BinaryUtils.isEmpty(fileName)) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("multipart/form-data");
                response.addHeader("Content-Disposition", (openWindow ? "attachment;" : "") + "filename=" + URLResolver.encode(fileName, Local.getCharset()));
            }

            try {
                OutputStream os = response.getOutputStream();
                InputStream is = resource.getInputStream();

                try {
                    FileSystem.copy(is, os);
                    os.flush();
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    resource.getFile().delete();
                }

                return null;
            } catch (IOException var12) {
                throw new ControllerException(var12);
            }
        } else {
            throw new ControllerException(" is not found resource '" + resource + "'! ");
        }
    }

}
